package com.zhf.service.impl;

import com.zhf.dao.ClassDao;
import com.zhf.dao.StudentDao;
import com.zhf.dao.impl.ClassDaoImpl;
import com.zhf.dao.impl.StudentDaoImpl;
import com.zhf.entity.Class1;
import com.zhf.entity.Page;
import com.zhf.entity.Student;
import com.zhf.exception.MyException;
import com.zhf.service.ClassService;

import java.util.List;

public class ClassServiceImpl implements ClassService {
    ClassDao classDao = new ClassDaoImpl();
    StudentDao studentDao = new StudentDaoImpl();
    @Override
    public List<Class1> queryAllClass(Page<Class1> page) {
        int count = classDao.queryCount();
        page.setTotalCount(count);
        int begin = (page.getCurrentPage() - 1) * page.getPageSize();
        int size = page.getPageSize();
        List<Class1> class1s = classDao.queryAllClass(begin, size);
        return class1s;
    }

    @Override
    public int insertClass1(Class1 class1) {
        Class1 class12 = classDao.queryClassByClassNo(class1.getClassNo());
        if(class12 == null){
            // 如果新增班级编号不存在，则新增
            boolean b = classDao.insertClass1(class1);
            if(b){
                return 1;
            }
        }
        return 0;
    }

    @Override
    public int updateClass1(Class1 class1) {
        Class1 class11 = classDao.queryClassByClassNo(class1.getClassNo());
        if(class11 != null){
            // 如果修改学生编号存在，则修改
            boolean b = classDao.updateClass(class1);
            if(b){
                return 1;
            }
        }
        return 0;
    }

    @Override
    public List<Class1> queryClassByClassNameAndGrade(String className, String grade) {
        List<Class1> class1s = classDao.queryClassByClassNameAndGrade("%" + className + "%","%" + grade + "%");
        return class1s;
    }

    @Override
    public boolean deleteClass(String[] classNos) {
        List<Class1> class1List = classDao.queryClassByClassNos(classNos);
        if(class1List != null && class1List.size() == classNos.length){
            // 检查学生表中，对应是否存在学生要删除得班级信息，如果存在，则不能删除
            List<Student> students = studentDao.queryStudentByClassNos(classNos);
            if(students == null || students.size() == 0){
                // 如果要删除得班级不存在，则可以删除班级信息
                int rowids = classDao.deleteClassByClassNos(classNos);
                if(rowids > 0){
                    return true;
                }
                else{
                    throw new MyException(102, "删除失败！");
                }
            }
            else{
                throw new MyException(103, "要删除的班级编号有学员信息存在！");
            }
        }
        else{
            throw new MyException(101, "要删除的班级编号不存在！");
        }
    }
}
